package com.xiaoxiang.auth.service.impl;

import com.xiaoxiang.auth.result.AuthResult;
import com.xiaoxiang.auth.entity.Role;
import com.xiaoxiang.auth.entity.User;
import com.xiaoxiang.auth.service.BaseAuthService;
import com.xiaoxiang.auth.util.JwtUtil;
import com.xiaoxiang.common.exception.CommonException;
import com.xiaoxiang.common.result.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户名密码认证服务
 * @author: haha
 * @date: 2022/2/7 18:53
 */
@Service("userAuthService")
public class UserAuthServiceImpl extends BaseAuthService {

    // 过期时间是3600秒，既是1个小时
    @Value("${token.expire}")
    private long expire;

    @Override
    public AuthResult auth(String username, String password) {
        User user = userService.queryByUsername(username);
        if (user == null) {
            throw new CommonException(ResultCodeEnum.USER_NOT_FOUND);
        }
        if (!user.getPassword().equals(password)) {
            throw new CommonException(ResultCodeEnum.PASSWORD_ERROR);
        }
        List<Role> roles = roleService.queryRoleByUserId(user.getId());
        String token = JwtUtil.createToken(user.getId(),
                roles.stream().map(Role::getId).collect(Collectors.toList()),
                roles.stream().map(Role::getRoleName).collect(Collectors.toList()), user.getUsername());

        AuthResult result = AuthResult.builder()
                .username(user.getUsername())
                .imgUrl(user.getImgUrl())
                .expire(System.currentTimeMillis() + 1000 * expire)
                .id(user.getId())
                .token(token).build();

        return result;
    }


}
